<script setup lang="ts">
import TodoHeader from './components/TodoHeader.vue';
import TodoMain from './components/TodoMain.vue';
import TodoFooter from './components/TodoFooter.vue';
import { ref, watch } from 'vue';

/** watch 数据持久化处理
 * 1.1 使用 watch 函数监听 list 数组
 * 1.2 当 list 数组发生改变就设置到本地存储中
 * 1.3 因为本地存储只能存字符串，list 数据是复杂数组对象，所以要 JSON.stringify 转成字符串再存
 * 1.3 因为 list 是 ref 定义的响应式复杂数据，所以要开启深度监听
 * 1.4 写死的 list 数据要变成从本地存储中获取
 * 1.5 存储在本地的数据是字符串，需要 JSON.parse 转成数组对象才能赋值给 list
 * 1.6 注意：从本地获取到的数组可能为空
 */

export interface ITodo {
  id: number;
  content: string;
  done: boolean;
}

const list = ref<ITodo[]>(JSON.parse(localStorage.getItem('todo-list') || '[]'));

const checkFn = (val: number) => {
  const todo = list.value.find(v => v.id === val);
  if (todo) todo.done = !todo.done;
};

const delFn = (val: number) => {
  list.value = list.value.filter(v => v.id !== val);
};

const addFn = (val: string) => {
  const todo: ITodo = { id: Date.now(), content: val, done: false };
  if (list.value.find(v => v.content === val)) return alert('不能重复添加相同的任务');
  list.value.unshift(todo);
};

const checkAll = (val: boolean) => {
  list.value.forEach(v => (v.done = val));
};
watch(
  list,
  () => {
    localStorage.setItem('todo-list', JSON.stringify(list.value));
  },
  { deep: true },
);
</script>

<template>
  <section class="todoapp">
    <TodoHeader @add-fn="addFn"></TodoHeader>
    <TodoMain :list="list" @check-fn="checkFn" @del-fn="delFn" @check-all="checkAll"></TodoMain>
    <TodoFooter :list="list"></TodoFooter>
  </section>
</template>
